package com.finance41.webtools.automerge;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;

/**
 * @author Ionut Bilica
 */
public class FileUtil {

	public static void appendFileContent(File file, StringBuilder stringBuilder) {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line;
			while ((line = reader.readLine()) != null) {
				stringBuilder.append(line);
				stringBuilder.append("\n");
			}
			reader.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void setFileContent(File file, String content) {
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			fileOutputStream.write(content.getBytes());
			fileOutputStream.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void removeAllFiles(File dir) {
		for (File file : dir.listFiles()) {
			if (file.isFile()) {
				file.delete();
			}
		}
	}

	/**
	 * Merges a list of file contents, adding the file name before each content in a C like comment.
	 * If one of the files is a directory, all files from that directory (no subfolder scanning) are added to the final result.
	 */
	public static String mergeFiles(File[] inputFiles) {
		StringBuilder stringBuilder = new StringBuilder();
		for (File file : inputFiles) {
			if (file.isFile()) {
				appendFile(stringBuilder, file);
			} else {
				for (File fileInDir : file.listFiles()) {
					if (!fileInDir.isFile())	continue;
					appendFile(stringBuilder, fileInDir);
				}
			}
		}

		return stringBuilder.toString();
	}

	private static void appendFile(StringBuilder stringBuilder, File file) {
		stringBuilder.append("\n\n\n\n/*\n\n\n\n\n           ");
		stringBuilder.append(file.getName());
		stringBuilder.append("\n*/\n\n");
		FileUtil.appendFileContent(file, stringBuilder);
	}
}
